package com.chj.comp.common.mqadmin.schedule;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.core.entity.MqMessageInfo;
import com.chj.comp.common.mqadmin.service.IMqMessageInfoService;
import com.chj.comp.common.rabbitmq.constant.MsgConstant;
import com.chj.comp.common.rabbitmq.constant.MsgTypeEnum;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：cuihui
 * @date ：Created in 2022/6/19
 * @description：轮询处理异常消息
 * @modified By：
 */
@Component
@Slf4j
public class MqMessageInfoHandler {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private IMqMessageInfoService mqMessageInfoService;

    @XxlJob(value = "mqadminJobHandler")
    public void mqadminJobHandler() {
        // 获取未正常消费的消息列表
        List<MqMessageInfo> errorMqMessageList = mqMessageInfoService.getErrorMqMessageList();
        if (!CollectionUtils.isEmpty(errorMqMessageList)){
            errorMqMessageList.forEach(errorMqMessage -> {
                String type = errorMqMessage.getType();
                String exchange = errorMqMessage.getExchange();
                String queue = errorMqMessage.getQueue();
                String routingKey = errorMqMessage.getRoutingKey();
                String messageInfo = errorMqMessage.getMessageInfo();
                Message message = JSON.parseObject(messageInfo, Message.class);
                // 消息重新发送
                if (type.equals(MsgTypeEnum.TYPE_1.getType()) || type.equals(MsgTypeEnum.TYPE_2.getType())){
                    // 简单队列、工作队列
                    rabbitTemplate.convertAndSend(queue, message);
                } else if (type.equals(MsgTypeEnum.TYPE_3.getType())){
                    // 广播类型
                    rabbitTemplate.convertAndSend(exchange, "", message);
                } else {
                    // 路由类型、主题类型
                    rabbitTemplate.convertAndSend(exchange, routingKey, message);
                }
                // 发送次数+1
                mqMessageInfoService.addMqMessageSendNum(errorMqMessage.getMessageId());
            });
        }

    }
}
